package com.ocm.core.dao.jpa;

import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.jpa.support.JpaDaoSupport;

import com.ocm.core.dao.GenericDao;
import com.ocm.core.domain.Persistable;


public class JpaGenericDao<T> extends JpaDaoSupport implements GenericDao<T> {

   private final  Class<T> persistentClass;

   public JpaGenericDao(final Class<T> persistentClass)
   {
      this.persistentClass = persistentClass;
   }

   public T findById(final Long id)
   {
      T result = getJpaTemplate().find(this.persistentClass, id);
      if (result == null) {
         throw new ObjectRetrievalFailureException(persistentClass, id);
      }
      return result;
   }

   public void remove(final Long id)
   {
      getJpaTemplate().remove(this.findById(id));
   }

   public void save(final T object)
   {
      if(((Persistable)object).getId() == null) {
         getJpaTemplate().persist(object);
      }
      else {
         getJpaTemplate().merge(object);
      }
   }

}
